package com.wondertek.poms.service.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IEquityTreeAbilityLogService;
import com.wondertek.poms.core.service.IEquityTreeMQLogService;
import com.wondertek.poms.core.service.IPomsExportLogService;
import com.wondertek.poms.core.service.IPrdInfoService;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.dao.po.EquityTreeAbilityLog;
import com.wondertek.poms.dao.po.EquityTreeMQLog;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.SystemConfig;
import com.wondertek.poms.service.util.BeanPropertiesUtil;
import com.wondertek.poms.service.vo.AbilityEquityReturnVo;
import com.wondertek.poms.service.vo.PrdInfoPublishVo;
import com.wondertek.poms.service.vo.PrdInfoVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author evan0213
 * @description 商品包管理web接口
 */
@Api(value = "PrdInfoController", description = "商品包管理 接口")
@RestController
@RequestMapping("prd-info")
@Slf4j
public class PrdInfoController {

	@Autowired
	private IPrdInfoService prdInfoService;
	@Autowired
	private BeanPropertiesUtil beanPropertiesUtil;
	@Autowired
	private ISystemConfigService systemConfigService;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private IEquityTreeMQLogService equityTreeMQLogService;
	@Autowired
	private IEquityTreeAbilityLogService equityTreeAbilityLogService;
	@Autowired
	private IPomsExportLogService pomsExportLogService;

	/**
	 * 查询商品包 列表
	 *
	 * @param prdInfoVo 查询的条件
	 * @param page      页码
	 * @param rows      查询的量
	 * @param sidx      排序列
	 * @param sord      拍寻方式
	 * @return 查询的结果
	 */
	@ApiOperation(value = "商品包 列表", notes = "商品包 列表")
	@GetMapping(value = "/list")
	@MethodLog(module = "商品包列表")
	public ResultBean list(PrdInfoVo prdInfoVo,
	                       @RequestParam(defaultValue = "1") int page,
	                       @RequestParam(defaultValue = "20") int rows,
	                       @RequestParam(defaultValue = "updateTime") String sidx,
	                       @RequestParam(defaultValue = "desc") String sord) {
		PrdInfo prdInfo = new PrdInfo();
		BeanUtils.copyProperties(prdInfoVo, prdInfo);
		Page<PrdInfo> pages = prdInfoService.findAll(prdInfo, page, rows, sord, sidx);
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	/**
	 * 商品包新增
	 *
	 * @param prdInfoVo vo对象
	 * @return 新增结果
	 */
	@ApiOperation(value = "商品包 新增", notes = "商品包 新增")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name", required = true),
			@ApiImplicitParam(name = "alias", required = false),
			@ApiImplicitParam(name = "description", required = false),
			@ApiImplicitParam(name = "spId", required = false),
			@ApiImplicitParam(name = "type", required = true),
			@ApiImplicitParam(name = "prdInfoType", required = true),
			@ApiImplicitParam(name = "bcId", required = false),
			@ApiImplicitParam(name = "firstProductInfoPackageId", required = true),
			@ApiImplicitParam(name = "productInfoPackageId", required = true),
			@ApiImplicitParam(name = "enterPrdInfoPriority", required = false),
			@ApiImplicitParam(name = "supportId", required = false),
			@ApiImplicitParam(name = "unSupportId", required = false),
			@ApiImplicitParam(name = "priority", required = true),
			@ApiImplicitParam(name = "creator", required = true),
			@ApiImplicitParam(name = "delegator", required = true),
			@ApiImplicitParam(name = "isBc", required = true),
			@ApiImplicitParam(name = "isOutput", required = true),
			@ApiImplicitParam(name = "autoVomsPublish", required = true),
	})
	@PostMapping("/add")
	@MethodLog(module = "商品包新增", insertDB = true, opterate = 1)
	public ResultBean add(@RequestBody PrdInfoVo prdInfoVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(prdInfoVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}

		if (isRepeat(prdInfoVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}

		PrdInfo prdInfo = new PrdInfo();
		BeanUtils.copyProperties(prdInfoVo, prdInfo);
		prdInfo.setIsPublish(Constants.PRD_INFO_PUBLISH_STATUS_1);
		prdInfo.setParent(1001004L);
		PrdInfo.putTimeAndUser(prdInfo);
		prdInfoService.save(prdInfo);
		return ResultBean.ok(prdInfo);
	}

	@GetMapping("/get-all-published")
	public ResultBean published() {
		List<PrdInfo> list = prdInfoService.findAllPublishedPrdInfo();
		return ResultBean.ok(list);
	}

	/**
	 * 判断是否重复
	 *
	 * @param prdInfoVo 需要判断的vo
	 * @return 重复结果
	 */
	private boolean isRepeat(PrdInfoVo prdInfoVo) {
		PrdInfo temp = new PrdInfo();
		CopyUtils.copyProperties(prdInfoVo, temp, "prdInfoId");
		beanPropertiesUtil.setNullIfStringIsBlank(temp);
		List<PrdInfo> list = prdInfoService.findAll(Example.of(temp));
		for (PrdInfo prdInfo : list) {
			PrdInfoVo vo = new PrdInfoVo();
			PrdInfoVo tempVo = new PrdInfoVo();
			CopyUtils.copyProperties(prdInfo, vo, "prdInfoId");
			CopyUtils.copyProperties(prdInfoVo, tempVo, "prdInfoId");
			beanPropertiesUtil.setNullIfStringIsBlank(tempVo);
			beanPropertiesUtil.setNullIfStringIsBlank(vo);
			if (vo.equals(tempVo)) {
				if (prdInfoVo.getPrdInfoId() == null || !Objects.equals(prdInfoVo.getPrdInfoId(), prdInfo.getPrdInfoId())) {
					return true;
				}
			}
		}
		return false;
	}


	@ApiOperation(value = "商品包 编辑", notes = "商品包 编辑")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "prdInfoId", required = true),
			@ApiImplicitParam(name = "name", required = false),
			@ApiImplicitParam(name = "alias", required = false),
			@ApiImplicitParam(name = "description", required = false),
			@ApiImplicitParam(name = "firstProductInfoPackageId", required = false),
			@ApiImplicitParam(name = "productInfoPackageId", required = false),
			@ApiImplicitParam(name = "enterPrdInfoPriority", required = false),
			@ApiImplicitParam(name = "autoVomsPublish", required = false),
	})
	@PutMapping("/edit")
	@MethodLog(module = "商品包编辑", insertDB = true, opterate = 2)
	public ResultBean edit(@RequestBody PrdInfoVo prdInfoVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(prdInfoVo, Constants.VALIDATE_UPDATE);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		PrdInfo prdInfo = new PrdInfo();
		BeanUtils.copyProperties(prdInfoVo, prdInfo);
		PrdInfo result = prdInfoService.merge(prdInfo);
		if (result.getIsPublish() != Constants.PRD_INFO_PUBLISH_STATUS_2) {
			return ResultBean.ok(result);
		} else {
			log.info("该商品包为已发布的商品包，编辑完需要进行发布");
			ArrayList<Long> list = new ArrayList<>();
			list.add(result.getPrdInfoId());
			return publish(list);
		}

	}


	/**
	 * 商品包撤回
	 *
	 * @return 撤回结果
	 */
	@PostMapping("/withdraw")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "list", required = true)
	})
	@MethodLog(module = "商品包撤回", insertDB = true, opterate = 5)
	public ResultBean withdrawPrdInfo(@RequestBody PrdInfoVo prdInfoVo) {
		List<PrdInfoPublishVo> voList = prdInfoVo.getList();
		for (PrdInfoPublishVo prdInfoPublishVo : voList) {
			List<String> messageList = ValidateFilter.getFilterMessage(prdInfoPublishVo, Constants.VALIDATE_DEFAULT);
			if (!messageList.isEmpty()) {
				return ResultBean.error(messageList.toString());
			}
		}
		for (PrdInfoPublishVo prdInfoPublishVo : voList) {
			if (prdInfoPublishVo.getIsPublish() != Constants.PRD_INFO_PUBLISH_STATUS_2) {
				return ResultBean.error("只有已发布的商品包才能撤回");
			}
		}
		List<Long> list = voList.stream().map(PrdInfoPublishVo::getId).collect(Collectors.toList());
		if (list.size() > 0) {
			SystemConfig basePathsConfig = systemConfigService.findByCkey("PUBLISH_INFO_BASE_PATH");
			if (StringUtils.isBlank(basePathsConfig.getValue())) {
				log.error("====发布产品包信息nas地址PUBLISH_INFO_BASE_PATH未配置====");
				return ResultBean.error("发布产品包信息nas地址未配置");
			}
			prdInfoService.updateIsPublish(Constants.PRD_INFO_PUBLISH_STATUS_3, list);
			log.info("*********修改商品包状态为已撤回成功*******");
			Map<String, Object> map = new HashMap<>();
			for (Long id : list) {
				PrdInfo prdInfo = prdInfoService.findByPrdInfoId(id);
				if (prdInfo != null) {
					map = prdInfoService.withdrawPrdInfo(prdInfo, basePathsConfig);
					log.info("同步给能力结束,商品包id为{},能力返回code{}", id, map.get("code"));

					log.info("开始发送能力mq##########");
					sendPowerMQ(prdInfo, Constants.PRD_INFO_OPR_CODE_2);
					log.info("结束发送能力mq##########");

					/*EquityTreeAbilityLog treeAbilityLog = new EquityTreeAbilityLog();
					try {
						ResultBean res = invokePower(treeAbilityLog, prdInfo, Constants.PRD_INFO_OPR_CODE_2);
						if ("1".equals(res.getCode())) {
							return res;
						}
					} catch (Exception e) {
						log.info("推送消息:treeAbilityLog{},pushContentId为{},结果失败!", treeAbilityLog.getId(), treeAbilityLog.getPushContentId());
						treeAbilityLog.setStatus(13);
						equityTreeAbilityLogService.save(treeAbilityLog);
					}*/
				}
			}
			return ResultBean.ok("撤回成功");
		} else {
			return ResultBean.error("商品包id不能为空");
		}
	}

	/**
	 * 商品包发布
	 *
	 * @return 返回结果
	 */
	@PostMapping("/publish")//depository
	@ApiImplicitParams({
			@ApiImplicitParam(name = "list", required = true)
	})
	@MethodLog(module = "商品包发布", insertDB = true, opterate = 4)
	public ResultBean publish(@RequestBody PrdInfoVo prdInfoVo) {
		List<PrdInfoPublishVo> list = prdInfoVo.getList();
		for (PrdInfoPublishVo prdInfoPublishVo : list) {
			List<String> messageList = ValidateFilter.getFilterMessage(prdInfoPublishVo, Constants.VALIDATE_DEFAULT);
			if (!messageList.isEmpty()) {
				return ResultBean.error(messageList.toString());
			}
		}
		/*for (PrdInfoPublishVo prdInfoPublishVo : list) {
			if (prdInfoPublishVo.getIsPublish() == Constants.PRD_INFO_PUBLISH_STATUS_2) {
				return ResultBean.error("不是已发布状态的商品包才能发布");
			}
		}*/
		List<Long> idList = list.stream().map(PrdInfoPublishVo::getId).collect(Collectors.toList());
		if (idList.size() > 0) {
			return publish(idList);
		} else {
			return ResultBean.error("商品包id不能为空");
		}

	}

	@GetMapping("/target")
	@MethodLog(module = "获取目标商品包")
	public ResultBean targetPrdInfo(Long prdInfoId) {
		List<PrdInfo> list = prdInfoService.findAllTargetPrdInfo(prdInfoId);
		return ResultBean.ok(list);
	}

	private ResultBean invokePower(EquityTreeAbilityLog treeAbilityLog, PrdInfo prdInfo, Integer oprCode) throws IOException {
		String abilityOn = systemConfigService.findByCkey("PUBLISH_ABILITY_SWITCH").getValue();
		if (abilityOn == null || !abilityOn.equals("on")) {
			log.info("==推送能力平台开关未配置或者已关闭==");
			return ResultBean.error("推送能力平台开关未配置或者已关闭");
		}
		String url = systemConfigService.findByCkey("PUBLISH_ABILITY_URL_EQUITY").getValue();
		if (StringUtils.isBlank(url)) {
			log.info("====推送能力平台接口URL[PUBLISH_ABILITY_URL_EQUITY]未配置======");
			return ResultBean.error("推送能力平台接口URL[PUBLISH_ABILITY_URL_EQUITY]未配置");
		}
		treeAbilityLog.setPushContentId(prdInfo.getPrdInfoId()).setPushRelationId(0L).setType("3")
				.setName(prdInfo.getName()).setXmlName(prdInfo.getName()).setOprCode(oprCode);//撤回操作码
		treeAbilityLog = equityTreeAbilityLogService.save(treeAbilityLog);
		AbilityEquityReturnVo abilityEquityReturnVo = new AbilityEquityReturnVo();
		abilityEquityReturnVo.setId(String.valueOf(treeAbilityLog.getId()));
		abilityEquityReturnVo.setType(String.valueOf(treeAbilityLog.getType()));
		abilityEquityReturnVo.setPushContentId(String.valueOf(treeAbilityLog.getPushContentId()));
		abilityEquityReturnVo.setXmlName(String.valueOf(treeAbilityLog.getXmlName()));
		abilityEquityReturnVo.setOprTime(DateUtil.format(treeAbilityLog.getOprTime(), "yyyyMMddHHmmss"));
		abilityEquityReturnVo.setOprCode(String.valueOf(treeAbilityLog.getOprCode()));
		ObjectMapper mapper = new ObjectMapper();
		HttpResponse response = HttpUtil.createPost(url).body(mapper.writeValueAsString(abilityEquityReturnVo),
				"application/json").execute();
		Map<String, String> rtMqp = mapper.readValue(response.body(), Map.class);
		String code = rtMqp.get("code");

		if ("0".equals(code)) {
			treeAbilityLog.setStatus(12);
			log.info("推送消息:treeAbilityLog{},pushContentId为{},结果成功!", treeAbilityLog.getId(), treeAbilityLog.getPushContentId());
		} else {
			treeAbilityLog.setStatus(13);
			log.info("推送消息:treeAbilityLog{},pushContentId为{},结果失败!", treeAbilityLog.getId(), treeAbilityLog.getPushContentId());
		}
		return ResultBean.ok();
	}

	private void sendPowerMQ(PrdInfo prdInfo, Integer oprCode) {
		Long id = prdInfo.getPrdInfoId();
		SystemConfig pushRelationIds = systemConfigService.findByCkey("EQUITY_TREE_QUEUES");
		if (StringUtils.isNotBlank(pushRelationIds.getValue())) {
			String[] arrayPushRelationId = pushRelationIds.getValue().split(",");
			log.info("发送MQ消息,商品包id为{}", id);
			for (String pushRelationId : arrayPushRelationId) {
				EquityTreeMQLog treeMQLog = new EquityTreeMQLog();
				treeMQLog.setPushContentId(id).setPushRelationId(Long.valueOf(pushRelationId)).setType("3")
						.setName(prdInfo.getName()).setXmlName(prdInfo.getName()).setOprCode(oprCode);
				EquityTreeMQLog equityTreeMQLog = equityTreeMQLogService.save(treeMQLog);
				try {
					jmsTemplate.convertAndSend(Constants.QUEUE_PRDINFO_PUBLISH + pushRelationId, equityTreeMQLog);
					equityTreeMQLog.setStatus(12);
					log.info("发送MQ消息成功,商品包id为{}", id);
				} catch (Exception e) {
					log.error("发送消息失败" + e);
					equityTreeMQLog.setStatus(13);
					log.info("发送MQ消息失败,商品包id为{}", id);
				}
				equityTreeMQLogService.save(equityTreeMQLog);
			}
		}
	}

	public ResultBean publish(List<Long> list) {
		String prdInfoConfig = systemConfigService.findByCkey("PARENT_PRD_INFO").getValue();
		List<String> prdInfoNameList = new ArrayList<String>();
		if (StringUtils.isNotBlank(prdInfoConfig)) {
			prdInfoNameList = Arrays.asList(prdInfoConfig.split(","));
		}
		Map<String, Object> resultMap = new HashMap<>();
		SystemConfig basePathsConfig = systemConfigService.findByCkey("PUBLISH_INFO_BASE_PATH");
		if (StringUtils.isBlank(basePathsConfig.getValue())) {
			log.error("====发布产品包信息nas地址PUBLISH_INFO_BASE_PATH未配置====");
			return ResultBean.error("发布产品包信息nas地址未配置");
		}
		SystemConfig urlConfig = systemConfigService.findByCkey("queryProductInfo");
		prdInfoService.updatePrdInfoPublish(Constants.PRD_INFO_PUBLISH_STATUS_2, LocalDateTimeUtil.now(), list);
		log.info("*********修改商品包状态为已发布成功*******");
		Map<String, Object> map = new HashMap<>();
		for (Long id : list) {
			PrdInfo prdInfo = prdInfoService.findByPrdInfoId(id);
			if (prdInfo != null) {
				map = prdInfoService.publishPrdInfo(prdInfo, basePathsConfig, urlConfig, resultMap, prdInfoNameList);
				log.info("同步给能力结束,商品包id为{}", id);

				log.info("生成xml文件开始#########");
				geneFile(prdInfo, map, basePathsConfig);
				log.info("生成xml文件结束#########");

				log.info("开始发送能力mq##########");
				sendPowerMQ(prdInfo, Constants.PRD_INFO_OPR_CODE_1);
				log.info("结束发送能力mq##########");

				/*EquityTreeAbilityLog treeAbilityLog = new EquityTreeAbilityLog();
				try {
					ResultBean res = invokePower(treeAbilityLog, prdInfo, Constants.PRD_INFO_OPR_CODE_1);
					if ("1".equals(res.getCode())) {
						return res;
					}
				} catch (Exception e) {
					log.info("推送消息:treeAbilityLog{},pushContentId为{},结果失败!", treeAbilityLog.getId(), treeAbilityLog.getPushContentId());
					treeAbilityLog.setStatus(13);
					equityTreeAbilityLogService.save(treeAbilityLog);
				}*/

			}
		}
		return ResultBean.ok("发布成功");
	}

	private void geneFile(PrdInfo prdInfo, Map<String, Object> map, SystemConfig basePathsConfig) {
		Long id = prdInfo.getPrdInfoId();
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding("utf-8");
		cfg.setEncoding(Locale.getDefault(), "utf-8");
		cfg.setStrictSyntaxMode(true);
		cfg.setNumberFormat("0");
		cfg.setClassForTemplateLoading(PrdInfoController.class, "/");

		String tmpPath = Constants.DEPOSITORY_PATH + File.separator + "publish"
				+ File.separator + prdInfo.getPrdInfoId().toString() + "-" + System.currentTimeMillis() + ".xml";
		File localFile = new File(tmpPath);
		if (!localFile.getParentFile().exists()) {
			localFile.getParentFile().mkdirs();
		}

		boolean sucFlag = false;
		OutputStreamWriter out = null;
		try {
			Template template = cfg.getTemplate("/template/vomsPrdInfoPublish.ftl");
			out = new OutputStreamWriter(new FileOutputStream(localFile), StandardCharsets.UTF_8);
			template.process(map, out);
			sucFlag = true;
		} catch (IOException | TemplateException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if (sucFlag) {
			String[] dp = basePathsConfig.getValue().split(",");
			for (String p : dp) {
				if (StringUtils.isNotBlank(p)) {
					FileUtil.copy(tmpPath, p + "/" + id + ".xml", true);
				}
			}

			String prePath = systemConfigService.findByCkey("PUBLISH_PREVIEW_PATH").getValue();
			if (StringUtils.isBlank(prePath)) {
				prePath = prePath.replace("content", "prdpackage");
				FileUtil.copy(tmpPath, prePath + "/" + id + ".xml", true);
			}
			Date publishTime = new Date();
			pomsExportLogService.updateLog("2", prdInfo.getPrdInfoId(), "1", publishTime);
		}
		if (localFile.exists()) {
			localFile.delete();
		}
	}

	/**
	 * 查询商品包 列表
	 *
	 * @param productInfoPackageId 二级产品id
	 * @return 商品包
	 */
	@ApiOperation(value = "商品包 列表", notes = "商品包 列表")
	@GetMapping(value = "/list-for-prd-cont")
	public ResultBean list(String productInfoPackageId) {
		if (StringUtils.isBlank(productInfoPackageId)) {
			return ResultBean.error("2级产品id不能为空");
		}
		return ResultBean.ok(prdInfoService.findAllByProductInfoPackageId(Long.parseLong(productInfoPackageId)));
	}

	/**
	 * 查询黑白名单专用商品包 列表
	 *
	 * @return 商品包
	 */
	@ApiOperation(value = "商品包 列表", notes = "商品包 列表")
	@GetMapping(value = "/list-for-black-white")
	public ResultBean listForBlackWhite() {
		return ResultBean.ok(prdInfoService.findForBlackWhite(2));
	}

}
